#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import wsgiref.handlers
import os
import Cookie
import killbills
from google.appengine.ext.webapp import template
from google.appengine.api import urlfetch
from google.appengine.ext import webapp

APP_NAME = "KillBills"

class MainHandler(webapp.RequestHandler):
  def get(self):
    template_values = {
      "appName": APP_NAME,
      "rules": killbills.getSpammerRules(),
      "screenName": killbills.getScreenName(self),
    }
    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, template_values))

class ReqHandler(webapp.RequestHandler):
  def get(self):
    token = killbills.reqAuth(self)
    if token:
      template_values = {
        "appName": APP_NAME,
        "token": token,
      }
      path = os.path.join(os.path.dirname(__file__), 'req.html')
      self.response.out.write(template.render(path, template_values))

class RunHandler(webapp.RequestHandler):
  def get(self):
    userInfo = killbills.runApp(self)
    if userInfo:
      followers = killbills.getFollowers(self, userInfo)
      spammers = killbills.getSpammers(followers)
      killbills.sendNotification(self, len(spammers))
      killbills.blockSpammers(self, spammers)
      template_values = {
        "appName": APP_NAME,
        "userInfo": userInfo,
        "followers": followers,
        "spammers": spammers,
      }
      path = os.path.join(os.path.dirname(__file__), 'run.html')
      self.response.out.write(template.render(path, template_values))

class LogOutHandler(webapp.RequestHandler):
  def get(self):
    killbills.logOut(self)
    self.redirect("/") 



def main():
  application = webapp.WSGIApplication(
                                        [
                                          ('/', MainHandler),
                                          ('/req', ReqHandler),
                                          ('/run', RunHandler),
                                          ('/logout', LogOutHandler),
                                        ],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
  main()
